package com.css.fxfzcpxx.modules.logRecord.service.impl;

import com.css.fxfzcpxx.base.user.service.UserService;
import com.css.fxfzcpxx.base.user.viewobjects.UserBaseInfoVO;
import com.css.fxfzcpxx.modules.logRecord.entity.SysAccessLog;
import com.css.fxfzcpxx.modules.logRecord.entity.SysLog;
import com.css.fxfzcpxx.modules.logRecord.repository.AccessLogRecordRepository;
import com.css.fxfzcpxx.modules.logRecord.repository.LogRecordRepository;
import com.css.fxfzcpxx.modules.logRecord.repository.impl.AccessLogRecordRepositoryImpl;
import com.css.fxfzcpxx.modules.logRecord.service.LogRecordService;
import com.css.fxfzcpxx.modules.logRecord.vo.SysLogVo;
import com.css.fxfzcpxx.util.PlatformDateUtils;
import com.css.fxfzcpxx.util.PlatformObjectUtils;
import com.css.fxfzcpxx.util.UUIDGenerator;
import com.css.fxfzcpxx.web.PlatformSessionContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:
 * @CreateTime: 2023/9/11 10:45
 * @Description:
 */
@Service
public class LogRecordServiceImpl implements LogRecordService {
    @Autowired
    LogRecordRepository logRecordRepository;
    @Autowired
    AccessLogRecordRepository accessLogRecordRepository;
    @Autowired
    private UserService userService ;

    private Map<String,String> getRequestHeader(HttpServletRequest request){
        Map<String,String> map = new HashMap<>();
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        map.put("remote_addr",request.getRemoteAddr());
        return map;
    }
    @Override
    @Transactional(rollbackFor = Exception.class )
    public void save(SysLogVo sysLogVo, HttpServletRequest request) {
        Map<String, String> headMap = getRequestHeader(request);
        SysLog sysLog = new SysLog();
        BeanUtils.copyProperties(sysLogVo, sysLog);
        UserBaseInfoVO user = null;
        if(PlatformObjectUtils.isNotEmpty(PlatformSessionContext.getUserID())){
            user = userService.getUser(PlatformSessionContext.getUserID());
        }
        //统计访问量（访问首页）
        if("/home/index".equals(sysLogVo.getPath())){
            String clientIp = getClientIpAddress(headMap);
            SysAccessLog data=accessLogRecordRepository.findByClientIp(clientIp);
            if(PlatformObjectUtils.isEmpty(data)){
                SysAccessLog sysAccessLog=new SysAccessLog();
                sysAccessLog.setLogId(UUIDGenerator.getUUID());
                sysAccessLog.setClientIp(clientIp);
                sysAccessLog.setOpTime(new Date());
                sysAccessLog.setPageView(1);
                if(PlatformObjectUtils.isNotEmpty(user)){
                    sysAccessLog.setOpUser(user.getUserName());
                }
                accessLogRecordRepository.save(sysAccessLog);

            }
        }
        SysLog data=logRecordRepository.findByDataType(sysLog.getDataType());
        if(PlatformObjectUtils.isNotEmpty(data)){
            logRecordRepository.updatePageView(data.getLogId(),data.getPageView()+1);
        }else {
            sysLog.setLogId(UUIDGenerator.getUUID());
            sysLog.setOpTime(PlatformDateUtils.getCurrentTimestamp());
            sysLog.setPageView(1);
            if(PlatformObjectUtils.isNotEmpty(user)){
                sysLog.setOpUser(user.getUserName());
            }
            logRecordRepository.save(sysLog);
        }
    }

//    //获取客户端ip
//    public String getClientIpAddress(HttpServletRequest request) {
//        String ipAddress = request.getHeader("X-Forwarded-For");
//        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getHeader("Proxy-Client-IP");
//        }
//        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getHeader("WL-Proxy-Client-IP");
//        }
//        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getHeader("HTTP_CLIENT_IP");
//        }
//        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
//        }
//        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
//            ipAddress = request.getRemoteAddr();
//        }
//        return ipAddress;
//    }
    //获取客户端ip
    public String getClientIpAddress(Map<String, String> headMap) {
        String ipAddress = headMap.get("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headMap.get("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headMap.get("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headMap.get("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headMap.get("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = headMap.get("remote_addr");
        }
        return ipAddress;
    }

}
